package com.heima.common.exception;

import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/*
*TODO 定义异常统一处理
*  */
@Slf4j
@Configuration
//spring mvc异常处理拦截注解
@RestControllerAdvice
public class ExceptionCatch {
    /*
    * todo 解决项目中所有异常拦截
    *       拦截所有 Exception异常
    * */
    @ExceptionHandler(Exception.class)
    public ResponseResult exception(Exception ex){
        ex.printStackTrace();
        log.error("ExceptionCatch ex:{}",ex);
        return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR,"你的网络异常请稍后再试");
    }
    /*
    * todo 拦截自定义异常
    *  */
    @ExceptionHandler(CustomException.class)
    public ResponseResult custException(CustomException ex){
        ex.printStackTrace();
        log.error("CustomException ex:{}", ex);
        AppHttpCodeEnum anEnum = ex.getAppHttpCodeEnum();
        return ResponseResult.errorResult(anEnum);
    }

    /**
     * 参数校验
     * @param ex
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseResult handleValidationException(MethodArgumentNotValidException ex){
        log.error("MethodArgumentNotValidException ex:{}",ex);
        ex.printStackTrace();
        return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,
                ex.getBindingResult().getFieldError().getDefaultMessage());
    }

}
